const app = getApp()

const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'


Page({
  data: {
    avatarUrl: defaultAvatarUrl,
    theme: wx.getSystemInfoSync().theme,
    userInfo: undefined
  },
  onLoad() {
    wx.onThemeChange((result) => {
      this.setData({
        theme: result.theme
      })
    })
  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail 
    this.setData({
      avatarUrl,
    })
  },
  submitInfo(e)
  {
    let userName = e.detail.value.uname;
    /**
     * 因为从设置页获取的头像Url是临时的，所以需要将其下载后上传到
     * 云储存中，并把链接存到数据库的评论中
     */
    wx.getImageInfo({
      src: this.data.avatarUrl,
      success: res=>
      {
        console.log(res);
        // 上传云储存
        wx.cloud.uploadFile({
          cloudPath: "avatars/"+userName+".jpg",
          filePath: res.path,
          success: res=>
          {
            this.setData({
              userInfo:{
                avatarUrl:"cloud://cloud1-9gdorijx26597ab7.636c-cloud1-9gdorijx26597ab7-1315072742/avatars/"+userName+".jpg",
                nickName: userName
              }
            })
            // 设置小程序的全局变量
            getApp().globalData.userInfo = this.data.userInfo;
            console.log(this.data.userInfo);
            // 触发主页面的函数，把isLogin设置为true，改变主页渲染方式
            const eventChannel = this.getOpenerEventChannel();
            eventChannel.emit("acceptIsLogin",true);
            wx.navigateBack({
              delta: 0,
            })
          }
        })
      }
    })
  }
})
